package game.goods;

import game.controller.Projectile;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.image.Image;

import java.util.HashMap;

import static game.basic.GameBase.*;
import static game.basic.GameBase.rightDir;
import static game.basic.Util.getImage;
import static game.main.GameApp.player;

public class OBJ_Fireball extends Projectile {

    HashMap<Integer, Image[]> fireMap = new HashMap<>();

    int spriteCounter = 0;//移动帧数计数器
    public int spriteNum = 0;//动画刷新的计数器

    public OBJ_Fireball() {
        readSpriteImage("/projectile/arm3_%s_%d.png");
        speedRock = 6;
        maxLife = 80;
        alive = false;
        life = 0;
    }


    public void readSpriteImage(String url) {
        Image[] up = new Image[3];
        Image[] down = new Image[3];
        Image[] left = new Image[3];
        Image[] right = new Image[3];

        String[] directions = {"u", "d", "l", "r"};
        int[] frames = {0, 1, 2};
        for (String d : directions) {
            for (int frame : frames) {
                String imagePath = String.format(url, d, frame + 1);
                switch (d) {
                    case "u" -> up[frame] = getImage(imagePath, tileSize*2, tileSize*2);
                    case "d" -> down[frame] = getImage(imagePath, tileSize*2, tileSize*2);
                    case "l" -> left[frame] = getImage(imagePath, tileSize*2, tileSize*2);
                    case "r" -> right[frame] = getImage(imagePath, tileSize*2, tileSize*2);
                }
            }
        }
        fireMap.put(upDir, up);
        fireMap.put(downDir, down);
        fireMap.put(leftDir, left);
        fireMap.put(rightDir, right);
    }


    @Override
    public void set(int worldX, int worldY, int direction) {
        this.worldX = worldX;
        this.worldY = worldY;
        this.direction = direction;
        this.life = this.maxLife;
    }

    @Override
    public void update() {
        if (--life >= 0 && alive) {
            switch (direction) {
                case upDir -> worldY -= speedRock;
                case downDir -> worldY += speedRock;
                case leftDir -> worldX -= speedRock;
                case rightDir -> worldX += speedRock;
            }
            if (++spriteCounter % 12 == 0) { // 每10帧改变一次 一秒5帧
                spriteNum = (spriteNum + 1) % 3;
                spriteCounter = 0;
            }
        } else {
            alive = false;
        }
    }

    @Override
    public void draw(GraphicsContext gc) {
        if (alive) {
            gc.drawImage(fireMap.get(direction)[spriteNum],
                    (worldX) - player.worldX + screenX,
                    (worldY) - player.worldY + screenY);
        }
    }
}
